package com.taotao.rop.service;

import com.rop.annotation.HttpAction;
import com.rop.annotation.NeedInSessionType;
import com.rop.annotation.ServiceMethod;
import com.rop.annotation.ServiceMethodBean;
import com.rop.session.SimpleSession;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.RopAppSecret;
import com.taotao.rop.database.domain.WechatMenu;
import com.taotao.rop.database.mapper.RopAppSecretMapper;
import com.taotao.rop.database.mapper.WechatMenuMapper;
import com.taotao.rop.manager.RopSessionManager;
import com.taotao.rop.response.BaseResponse;
import com.taotao.wechat.business.MenuUtil;
import com.taotao.wechat.menu.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@ServiceMethodBean(httpAction = HttpAction.POST, version = "1.0")
public class WechatMenuService {
    @Autowired
    private WechatMenuMapper wechatMenuMapper;
    @Autowired
    private RopAppSecretMapper appSecretMapper;

    @ServiceMethod(method = "wechatMenu.list", needInSession = NeedInSessionType.NO)
    public Object listMenu(WechatMenu request) {
        WechatMenu menuCondition = new WechatMenu();
        menuCondition.setParentId(0L);
        String appId = ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_APP_ID).toString();
        if (request.getAppId() != null) {
            appId = request.getAppId();
        }
        menuCondition.setAppId(appId);
        List<WechatMenu> parentMenuList = wechatMenuMapper.getList(menuCondition);
        List<WechatMenu> theParentMenuList = new ArrayList<WechatMenu>();
        for (WechatMenu parentMenu : parentMenuList) {
            menuCondition.setParentId(parentMenu.getId());
            List<WechatMenu> subMenuList = wechatMenuMapper.getList(menuCondition);
            parentMenu.setSubMenus(subMenuList);
            int enableSubMenuCount = 0;
            for (WechatMenu wechatMenu : subMenuList) {
                if (wechatMenu.getStatus().equals(Constant.STATUS_ENABLE)) {
                    enableSubMenuCount++;
                }
            }
            parentMenu.setName(parentMenu.getName() + " (" + enableSubMenuCount + ")");
            theParentMenuList.add(parentMenu);
        }

        BaseResponse<List<WechatMenu>> response = new BaseResponse<List<WechatMenu>>();
        response.setSuccess(true);
        response.setMsg("" + theParentMenuList.size());
        response.setData(theParentMenuList);
        return response;
    }

    @ServiceMethod(method = "wechatMenu.insert", needInSession = NeedInSessionType.NO)
    public Object insertMenu(WechatMenu request) {
        String appId = ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_APP_ID).toString();
        if (request.getAppId() != null) {
            appId = request.getAppId();
        }
        request.setAppId(appId);
        Integer count = wechatMenuMapper.insertOne(request);

        BaseResponse<Integer> response = new BaseResponse<Integer>();
        response.setSuccess(true);
        response.setData(count);
        return response;
    }

    @ServiceMethod(method = "wechatMenu.update", needInSession = NeedInSessionType.NO)
    public Object updateMenu(WechatMenu request) {
        String appId = ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_APP_ID).toString();
        if (request.getAppId() != null) {
            appId = request.getAppId();
        }
        request.setAppId(appId);
        Integer count = wechatMenuMapper.updateOne(request);

        BaseResponse<Integer> response = new BaseResponse<Integer>();
        response.setSuccess(true);
        response.setData(count);
        return response;
    }

    /**
     * 生成微信菜单
     */
    @ServiceMethod(method = "wechatMenu.generate")
    public Object generateMenu(WechatMenu request) {
        boolean isGenerate = true;
        StringBuilder sb = new StringBuilder();

        String appId = ((SimpleSession)request.getRopRequestContext().getSession()).getAttribute(RopSessionManager.KEY_APP_ID).toString();
        if (request.getAppId() != null) {
            appId = request.getAppId();
        }
        if(appId.equals(MyRopClient.APP_ID)) {
            RopAppSecret condition = new RopAppSecret();
            condition.setStatus(Constant.STATUS_ENABLE);
            List<RopAppSecret> apps = appSecretMapper.getList(condition);
            int failure = 0;
            for (RopAppSecret app : apps) {
                if (!app.getAppId().equals(MyRopClient.APP_ID)) {
                    if(!generateMenuForApp(app.getAppId())){
                        sb.append(app.getAppId()).append("\n");
                        failure ++;
                    }
                }
            }
            if (failure > 0) {
                isGenerate = false;
            }
        } else {
            isGenerate = generateMenuForApp(appId);
        }

        BaseResponse<Menu> response = new BaseResponse<Menu>();
        response.setSuccess(isGenerate);
        if (isGenerate) {
            response.setMsg("发布成功，24小时后生效");
        } else {
            response.setMsg(sb.toString() + "发布失败，请核对微信菜单生成规则");
        }
        return response;
    }

    private boolean generateMenuForApp(String appId) {
        Menu menu = new Menu();
        Button[] buttons = new Button[3];
        List<Button> buttonList = new ArrayList<Button>();

        WechatMenu menuCondition = new WechatMenu();
        menuCondition.setParentId(0L);
        menuCondition.setAppId(appId);
        menuCondition.setStatus(Constant.STATUS_ENABLE);
        List<WechatMenu> parentMenuList = wechatMenuMapper.getList(menuCondition);
        int menuCount = parentMenuList.size() > buttons.length ? buttons.length : parentMenuList.size();
        for (int i = 0; i < menuCount; i++) {
            if (parentMenuList.get(i).getType().equalsIgnoreCase("complex")) {
                ComplexButton complexButton = new ComplexButton();
                complexButton.setName(parentMenuList.get(i).getName());

                List<Button> sub_button = new ArrayList<Button>();
                menuCondition.setParentId(parentMenuList.get(i).getId());
                List<WechatMenu> subMenuList = wechatMenuMapper.getList(menuCondition);
                int count = subMenuList.size() > 5 ? 5 : subMenuList.size();
                for (int j = 0; j < count; j++) {
                    if (appId.equals("wx940fdc566fac172a")
                            && "9999".equals(subMenuList.get(j).getKey())) {
                        continue;
                    }
                    if (subMenuList.get(j).getType().equalsIgnoreCase("view")) {
                        ViewButton viewButton = new ViewButton();
                        viewButton.setType("view");
                        viewButton.setUrl(subMenuList.get(j).getUrl());
                        viewButton.setName(subMenuList.get(j).getName());
                        sub_button.add(viewButton);
                    } else if (subMenuList.get(j).getType().equalsIgnoreCase("click")
                            || subMenuList.get(j).getType().equalsIgnoreCase("location_select")) {
                        ClickButton clickButton = new ClickButton();
                        clickButton.setType(subMenuList.get(j).getType().toLowerCase());
                        clickButton.setKey(subMenuList.get(j).getKey());
                        clickButton.setName(subMenuList.get(j).getName());
                        sub_button.add(clickButton);
                    }
                }
                Button[] subButtons = new Button[sub_button.size()];
                complexButton.setSub_button(sub_button.toArray(subButtons));
                buttonList.add(complexButton);
            } else if (parentMenuList.get(i).getType().equalsIgnoreCase("view")) {
                ViewButton viewButton = new ViewButton();
                viewButton.setType("view");
                viewButton.setUrl(parentMenuList.get(i).getUrl());
                viewButton.setName(parentMenuList.get(i).getName());
                buttonList.add(viewButton);
            } else if (parentMenuList.get(i).getType().equalsIgnoreCase("click")
                    || parentMenuList.get(i).getType().equalsIgnoreCase("location_select")) {
                ClickButton clickButton = new ClickButton();
                clickButton.setType(parentMenuList.get(i).getType().toLowerCase());
                clickButton.setKey(parentMenuList.get(i).getKey());
                clickButton.setName(parentMenuList.get(i).getName());
                buttonList.add(clickButton);
            }
            if (buttonList.size() >= buttons.length) {
                break;
            }
        }
        menu.setButton(buttonList.toArray(buttons));

        //请求微信接口发布菜单
        return MenuUtil.generateMenu(menu, appId);
    }
}
